//
//  DYJShortViewController.m
//  Piece
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "DYJShortViewController.h"
#import "DYJShortContentModel.h"
#import "DYJShortContentHeaderTableViewCell.h"
#import "DYJShortContentTableViewCell.h"
#import "ZHNetworkHandler.h"


#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "JZShareCustom.h"
#import "DYJReadContentFooterTableViewCell.h"
#import "XZHMovieCommentModel.h"
#import "XZHMovieCommentTableViewCell.h"
#import "FeHourGlass.h"
#import "ZHArchiverTools.h"
@interface DYJShortViewController ()<UITableViewDelegate, UITableViewDataSource, DYJReadContentFooterViewDelegate>
@property (nonatomic, strong) UITableView *shortTableView;
@property (nonatomic, strong) DYJShortContentModel *shortContentModel;
@property (nonatomic, strong) NSMutableArray *commentDataArray;
@property (strong, nonatomic) FeHourGlass *hourGlass;
@end

@implementation DYJShortViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"短篇";
    [self createShortTableView];
    [self getShortContentData];
 //   [self createReadContentFooterView];
}
#pragma mark -- 创建tableView
- (void)createShortTableView
{
    self.shortTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
    self.shortTableView.separatorStyle = 0;
    self.shortTableView.delegate = self;
    self.shortTableView.dataSource = self;
    [self.view addSubview:_shortTableView];
    
    //注册cell
    [self.shortTableView registerNib:[UINib nibWithNibName:@"DYJShortContentHeaderTableViewCell" bundle:nil] forCellReuseIdentifier:@"headerCell"];
    
    [self.shortTableView registerNib:[UINib nibWithNibName:@"DYJShortContentTableViewCell" bundle:nil] forCellReuseIdentifier:@"contentCell"];
    
    [self.shortTableView registerNib:[UINib nibWithNibName:@"XZHMovieCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"commentCell"];
}
- (void)myTask
{
    // Do something usefull in here instead of sleeping ...
    sleep(6);
}

#pragma mark -- 获取数据
- (void)getShortContentData
{
    
    _hourGlass = [[FeHourGlass alloc] initWithView:self.shortTableView];
    [self.view addSubview:_hourGlass];
    [_hourGlass showWhileExecutingBlock:^{
        [self myTask];
    } completion:^{
        
        
    }];
    NSString *urlStr = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/essay/%@", _shortId];
    [ZHNetworkHandler getDataByURLString:urlStr WithBodyString:nil WithHeaderDic:nil WithResponse:0 WithSuccess:^(id result) {
        NSDictionary *dictionary = (NSDictionary *)result;
        [ZHArchiverTools archiverObject:dictionary ByKey:@"shortCache" WithPath:@"short.plist"];
        NSDictionary *dataDic = [dictionary objectForKey:@"data"];
        self.shortContentModel = [[DYJShortContentModel alloc] initWithDic:dataDic];
        
        [self.shortTableView reloadData];
        [_hourGlass removeFromSuperview];
    } WithFailure:^(NSError *error) {
        NSDictionary *dictionary = [ZHArchiverTools unarchiverObjectByKey:@"shortCache" WithPath:@"short.plist"];
        if (dictionary == nil) {
            
        }
        else
        {
            NSDictionary *dataDic = [dictionary objectForKey:@"data"];
            self.shortContentModel = [[DYJShortContentModel alloc] initWithDic:dataDic];
            
            [self.shortTableView reloadData];
            [_hourGlass removeFromSuperview];
        }
    }];
   
    _commentDataArray = [NSMutableArray array];
    NSString *commentUrl = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praise/essay/%@/0", _shortId];
    [ZHNetworkHandler getDataByURLString:commentUrl WithBodyString:nil WithHeaderDic:nil WithResponse:0 WithSuccess:^(id result) {
        NSDictionary *dictionary = (NSDictionary *)result;
        [ZHArchiverTools archiverObject:dictionary ByKey:@"shortCommentCache" WithPath:@"shortComment.plist"];
        NSDictionary *dataDic = [dictionary valueForKey:@"data"];
        NSArray *dataArray = [dataDic valueForKey:@"data"];
        for (NSDictionary *dic in dataArray) {
            XZHMovieCommentModel *commentModel = [[XZHMovieCommentModel alloc] initWithDic:dic];
            [_commentDataArray addObject:commentModel];
        }
        [_shortTableView reloadData];
    } WithFailure:^(NSError *error) {
        NSDictionary *dictionary = [ZHArchiverTools unarchiverObjectByKey:@"shortCommentCache" WithPath:@"shortComment.plist"];
        if (dictionary == nil) {
            
        }
        else
        {
            NSDictionary *dataDic = [dictionary valueForKey:@"data"];
            NSArray *dataArray = [dataDic valueForKey:@"data"];
            for (NSDictionary *dic in dataArray) {
                XZHMovieCommentModel *commentModel = [[XZHMovieCommentModel alloc] initWithDic:dic];
                [_commentDataArray addObject:commentModel];
            }
            [_shortTableView reloadData];

        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }
    return _commentDataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 130;
        }
        else if (indexPath.row == 1)
        {
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[_shortContentModel.hp_content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
            NSString *contentStr = [attributedString string];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil];
            CGRect rect = [contentStr boundingRectWithSize:CGSizeMake(ScreenWidth - 35, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
            
            return rect.size.height + 30;
            
        }
        else return 49;

    }
    else
    {
        XZHMovieCommentModel *commentModel = [_commentDataArray objectAtIndex:indexPath.row];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12], NSFontAttributeName, nil];
        CGRect rect = [commentModel.content boundingRectWithSize:CGSizeMake(ScreenWidth - 63, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
        
        return rect.size.height + 100;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            DYJShortContentHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"headerCell"];
            cell.model = _shortContentModel;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        else if (indexPath.row == 1)
        {
            DYJShortContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"contentCell"];
            cell.model = _shortContentModel;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }
        else
        {
            DYJReadContentFooterTableViewCell *cell = [[DYJReadContentFooterTableViewCell alloc] init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            cell.likeCountsLabel.text = [NSString stringWithFormat:@"%ld", _shortContentModel.praisenum];
            cell.authorIntroductionLabel.text = _shortContentModel.hp_author_introduce;
            return cell;
        }

    }
    else
    {
        XZHMovieCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell"];
        cell.model = [_commentDataArray objectAtIndex:indexPath.row];
        cell.selectionStyle = 0;
        return cell;
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [_hourGlass showWhileExecutingBlock:^{
       // [self myTask];
    } completion:^{
        
        
    }];

    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}
- (void)phushShareView
{
    //1、创建分享参数
    NSArray* imageArray = @[[UIImage imageNamed:@"xph"]];
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:[NSString stringWithFormat:@"[%@] %@",_shortContentModel.hp_title, _shortContentModel.web_url]
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://www.kohmax.com"]
                                          title:@"JZShare"
                                           type:SSDKContentTypeAuto];
        
        
        //调用自定义分享
        [JZShareCustom shareWithContent:shareParams Url:_shortContentModel.web_url Title:_shortContentModel.hp_title Type:@"short" HomeModel:nil MovieModel:nil];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
